import locale from "antd/es/date-picker/locale/zh_CN";
import { InputProps } from "antd/lib/input";
import {
  Form,
  Row,
  Col,
  Input,
  Button,
  InputNumber,
  AutoComplete,
  Select,
  DatePicker,
  TreeSelect,
  Switch,
  Cascader,
  TimePicker,
} from "antd";

const RangePicker: any = DatePicker.RangePicker;
const DDatePicker: any = DatePicker;
const { Option } = Select;
const { TreeNode } = TreeSelect;

export interface searchListProps extends Omit<InputProps, "tagName"> {
  tagFName: string;
  key: string;
  label?: string;
  [key: `sf_${string}`]: any;
}

export interface SearchProps {
  searchList: searchListProps[];
  autoSearch?: boolean;
  onSearch?: Function;
  onReset?: Function;
  [key: string]: any;
}

export const SearchForm = ({
  searchList,
  autoSearch = false,
  onSearch,
  onReset,
  ...props
}: SearchProps) => {
  const [form] = Form.useForm();
  const onFinish = (values: { [key: string]: string | number | undefined }) => {
    onSearch?.(values);
  };

  // const onDiscountChange = debounce((e) => {
  //   autoSearch && onFinish(form.getFieldsValue());
  // }, 1500);

  const lisLen: number = searchList.length;
  const span: number = lisLen >= 5 ? 4 : (24 - 2.5) / lisLen;
  // eslint-disable-next-line complexity
  const getFormElement = (tagFName: string, oItem: any) => {
    let item: any = {};
    for (let key in oItem) {
      if (oItem.hasOwnProperty(key)) {
        if (key !== "sf_defaultValue" && key !== "tagFName") {
          item[key] = oItem[key];
        }
      }
    }
    item = {
      ...item,
      onChange: (e: any) => autoSearch && onFinish(form.getFieldsValue()),
      onSelect: () => autoSearch && onFinish(form.getFieldsValue()),
    };

    switch (tagFName) {
      case "input":
        return <Input allowClear {...item} />;
      case "inputNumber":
        return <InputNumber min={0} {...item} />;
      case "autoComplete":
        return (
          <AutoComplete
            allowClear
            options={item.optins}
            filterOption={(inputValue: any, option: any) => {
              return (
                option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !==
                -1
              );
            }}
            {...item}
          />
        );
      case "switch":
        return (
          <Switch checkedChildren="On" unCheckedChildren="Off" {...item} />
        );
      case "select":
        // eslint-disable-next-line no-case-declarations
        const selectList = item.sf_list || item.sf_selectlist || [];
        return (
          <Select allowClear {...item}>
            {item.render?.()}
            {!item.render &&
              selectList.map((cl: any) => {
                const oName = cl.key || cl.text || cl.value;
                return (
                  <Option key={cl.id} value={cl.id}>
                    {oName}
                  </Option>
                );
              })}
          </Select>
        );
      case "treeSelect":
        // eslint-disable-next-line no-case-declarations
        const treeSelectList = item.sf_list || item.sf_selectlist || [];
        return (
          <TreeSelect allowClear multiple {...item}>
            {item.render?.()}
            {!item.render &&
              treeSelectList.map((cl: any) => {
                const nodeName = cl.key || cl.value;
                return (
                  <TreeNode key={cl.id} value={cl.id} title={nodeName}>
                    {(cl.children || []).map((chil: any) => {
                      const subnodeName = chil.key || chil.value;
                      return (
                        <TreeNode
                          key={chil.id}
                          value={chil.id}
                          title={subnodeName}
                        />
                      );
                    })}
                  </TreeNode>
                );
              })}
          </TreeSelect>
        );
      case "datePicker":
        return <DDatePicker locale={locale} {...item} />;
      case "rangePicker":
        return <RangePicker locale={locale} {...item} />;
      case "timePicker":
        return <TimePicker locale={locale} {...item} />;
      case "rangeTimePicker":
        return <TimePicker.RangePicker {...item} />;
      case "cascader":
        return <Cascader {...item} />;
      default:
        return "";
    }
  };

  return (
    <Form form={form} name="advanced_search" {...props} onFinish={onFinish}>
      <Row gutter={24}>
        {searchList.map((item: any, i: number) => {
          const tagName = item.tagFName || "";
          // .toLowerCase();

          if (tagName !== "input" && item.rules) {
            // delete item.rules;
            item.rules = null;
          }

          const itemName = item.key;
          return (
            <Col
              span={tagName === "switch" ? 2.5 : span}
              key={item.key + i}
              style={{
                minWidth: tagName === "switch" ? "auto" : "200px",
              }}
            >
              <Form.Item
                name={itemName}
                label={item.label}
                rules={item.rules ? [item.rules] : []}
              >
                {getFormElement(tagName, item)}
              </Form.Item>
            </Col>
          );
        })}

        <Col
          span={2.5}
          style={{ minWidth: "100px", textAlign: "right", flex: "auto" }}
        >
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button
            style={{ margin: "0 8px" }}
            onClick={() => {
              form.resetFields();
              onReset?.();
            }}
          >
            重置
          </Button>
        </Col>
      </Row>
    </Form>
  );
};
